import React, { useEffect, Fragment, useState } from 'react';
import { connect } from 'umi';
import moment from 'moment';
import { eventTrack } from '@/utils/track';
import { get as getPath } from 'object-path';
import { formatMessage } from 'umi';
import { QuickForm } from 'vv-frontend-components';
import { Row, Col, Card, Empty, Form, Button, Spin } from 'antd';
import Locale from '@/utils/locale';
import QueryPage from '@/components/QueryPage';
import DateRange from '@/components/DateRange';
import ReactEcharts from '@/components/Echarts';
import themes from '@/theme';
import CompanyDepart from '@/components/CompanyDepart';
import { exists } from '@/utils/utils';
import request from '@/utils/request';
import PageRouter from '@/components/PageRouter/PageRouter';
import { withRoutePage } from '@/utils/enhanceUtils';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import { everyEmpty } from './utils';
import styles from './index.less';

const { locale } = new Locale('stat.overtime');
const formatStartDate = date => {
    if (date) return moment(date);
    return moment()
        .subtract(1, 'M')
        .startOf('month');
};

const formatEndDate = date => {
    if (date) return moment(date);
    return moment()
        .subtract(1, 'M')
        .endOf('month');
};

const Result = ({ form, location, result, dispatch, loading, route }) => {
    const { query } = location;
    const { departmentId, companyId, startTime, endTime, dateType, quarter } = query;
    const user = localStorage.getItem('user');
    const [innerLoading, setInnerLoading] = useState(false);

    const { data } = result;
    const config = [
        {
            field: 'companyDepart',
            label: '公司部门',
            config: {
                initialValue: {
                    companyId,
                    departmentId
                }
            },
            component: (
                <CompanyDepart
                    customDepartmentRequest={{
                        url: '/api/oa/v1/department/getemployeeanalysetree'
                    }}
                    permissionCode={route.code}
                />
            )
        },
        {
            field: 'date',
            config: {
                initialValue: {
                    range: [formatStartDate(startTime), formatEndDate(endTime)],
                    type: !dateType ? 'month' : dateType,
                    quarter: quarter ? Number(quarter) : 1
                }
            },
            component: <DateRange allowClear={false} />
        },
        {
            component: (
                <div>
                    <Button type="primary" htmlType="submit" loading={loading}>
                        {locale('form.search', false)}
                    </Button>
                </div>
            )
        }
    ];
    const handleSubmit = () => {
        form.validateFields(async (err, values) => {
            const { date = { range: [] } } = values;
            if (err) return;
            dispatch({
                type: 'result/getResult',
                payload: {
                    companyId: getPath(values, 'companyDepart.companyId', null),
                    departmentId: getPath(values, 'companyDepart.departmentId', ''),
                    beginTime: date.range && date.range[0] ? moment(date.range[0]).format('YYYY-MM-DD 00:00:00') : '',
                    endTime: date.range && date.range[1] ? moment(date.range[1]).format('YYYY-MM-DD 23:59:59') : ''
                }
            });
            eventTrack({
                // 埋点
                eventName: 'personnel_management_recruit_analysis_search_click',
                eventProps: {
                    label: '招聘结果分析-搜索',
                    key_words: JSON.stringify(values)
                }
            });
        });
    };
    const getOption = () => {
        // 只展示有数据的结果
        const innerData = data.filter(v => v.value !== 0);
        // 处理颜色：按名字和颜色对应
        const recruitColor = data
            .map(item => item.name)
            .map((item, index) => ({
                name: item,
                color: themes[index]
            }));
        const findColor = name => recruitColor.find(v => v.name === name) || { color: '#3BA0FF' };
        return {
            series: [
                {
                    name: '招聘结果分析',
                    type: 'funnel',
                    width: '80%',
                    data: innerData.map(item => ({
                        name: item.name,
                        value: item.value,
                        itemStyle: {
                            color: findColor(item.name).color
                        }
                    })),
                    left: 0,
                    top: 20,
                    maxSize: '45%',
                    label: {
                        normal: {
                            formatter: '{b}  {c}'
                        }
                    },
                    labelLine: {
                        normal: {
                            show: false
                        }
                    }
                }
            ]
        };
    };

    /**
     * 测试希望 只有一项时做100%展示 还想保留所有的图例，所有就有了这个`getLegend`
     */
    const getLegend = () => ({
        legend: {
            orient: 'vertical',
            left: 0,
            top: 20,
            align: 'left',
            type: 'scroll',
            data: data.map(item => item.name)
        },
        series: [
            {
                name: '访问来源',
                type: 'pie',
                radius: '0%',
                tooltip: {
                    show: false
                },
                center: ['50%', '60%'],
                data,
                label: {
                    normal: {
                        show: false
                    }
                },
                animation: false
            }
        ]
    });
    const init = async () => {
        setInnerLoading(true);
        const newResult = await request('/api/oa/v1/department/getemployeeanalysetree', {
            params: {
                companyId: user.companyId,
                permissionUrl: route.code
            }
        });
        setInnerLoading(false);
        // 如果当前用户部门id没有匹配上时才选中列表第一个
        if (newResult && newResult.code === 10000) {
            if (!exists(newResult.data, 'id', Number(departmentId || user.departmentId))) {
                form.setFieldsValue({
                    companyDepart: {
                        ...form.getFieldValue('companyDepart'),
                        departmentId: undefined
                    }
                });
            } else {
                form.setFieldsValue({
                    companyDepart: {
                        ...form.getFieldValue('companyDepart'),
                        departmentId: undefined
                    }
                });
            }
            handleSubmit();
        }
    };
    useEffect(() => {
        init();
        return () => {
            dispatch({
                type: 'result/clear'
            });
        };
    }, []);
    // Card title自定义样式属性
    const headStyle = {
        fontSize: '16px',
        lineHeight: '22px'
    };
    const { pathname } = location;
    const tabType = pathname.includes('office') ? 'recruit' : 'recruitStat';
    return (
        <PageHeaderWrapper>
            <PageRouter type={tabType}>
                <QueryPage
                    style={{
                        overflow: 'hidden'
                    }}
                    className={styles.queryWn}
                    background="transparent"
                    form={
                        <Card bordered={false} title="招聘结果分析" headStyle={headStyle}>
                            <Spin spinning={innerLoading}>
                                <Form
                                    layout="inline"
                                    onSubmit={e => {
                                        e.preventDefault();
                                        handleSubmit();
                                    }}
                                >
                                    <QuickForm form={form} config={config} />
                                </Form>
                            </Spin>
                        </Card>
                    }
                />
                <div className={styles.slideDiv}>
                    <Card
                        bordered={false}
                        loading={innerLoading || loading}
                        title="招聘结果分析"
                        headStyle={{
                            border: 'none'
                        }}
                        className={styles.cardTitle}
                    >
                        {!everyEmpty(data) ? (
                            <Fragment>
                                <Row>
                                    <Col md={{ span: 12 }}>
                                        <ReactEcharts
                                            style={{
                                                width: '100%'
                                            }}
                                            option={getOption(data)}
                                        />
                                    </Col>
                                    <Col md={{ span: 12 }}>
                                        <ReactEcharts
                                            style={{
                                                width: '100%'
                                            }}
                                            option={getLegend(data)}
                                        />
                                    </Col>
                                </Row>
                            </Fragment>
                        ) : (
                            <Empty
                                image={Empty.PRESENTED_IMAGE_SIMPLE}
                                description={formatMessage({
                                    id: 'stat.name.zwsj'
                                })}
                            />
                        )}
                    </Card>
                </div>
            </PageRouter>
        </PageHeaderWrapper>
    );
};
export default withRoutePage(
    connect(({ result, loading }) => ({
        result,
        loading: loading.models.result
    }))(Form.create()(Result))
);
